const { ListNode } = require('./base')

const removeNthFromEnd1 = function (head, n) {
  let fast = head
  let slow = head
  let k = n
  while (k > 0) {
    fast = fast.next
    k--
  }
  while (fast) {
    slow = slow.next
    fast = fast.next
  }
  if (slow === head) {
    return head.next
  } else {
    let preNode = head
    while (preNode.next !== slow) {
      preNode = preNode.next
    }
    preNode.next = slow.next
    return head
  }
}

const removeNthFromEnd2 = function (head, n) {
  let dummy = new ListNode(-1)
  let fast = dummy
  let slow = dummy
  dummy.next = head
  for (let i = 0; i < n + 1; i++) {
    // n+1
    fast = fast.next
  }
  while (fast) {
    // N-(n+1)+1 = N-n
    slow = slow.next
    fast = fast.next
  }
  slow.next = slow.next.next
  return dummy.next
}
